package com.wutma.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wutma.common.core.constants.Constants;
import com.wutma.common.core.enums.ResultCode;
import com.wutma.common.security.exception.ServiceException;
import com.wutma.friend.domain.question.entity.Question;
import com.wutma.friend.domain.question.vo.QuestionESVO;
import com.wutma.friend.mapper.question.QuestionMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class QuestionEsManager {

    @Autowired
    private RestHighLevelClient esClient;

    @Autowired
    private QuestionMapper questionMapper;

    public QuestionESVO getQuestionEsVO(Long questionId) {

        try {
            // 先从ES中查询结果
            GetRequest request = new GetRequest(Constants.ES_INDEX);
            request.id(questionId.toString());
            GetResponse response = null;
            response = esClient.get(request, RequestOptions.DEFAULT);
            QuestionESVO questionESVO = new QuestionESVO();
            if (response != null) {
                String questionJson = response.getSourceAsString();
                questionESVO = JSON.parseObject(questionJson, QuestionESVO.class);
            }
            else {
                questionESVO = null;
            }
            return questionESVO;

        } catch (IOException e) {
            throw new ServiceException(ResultCode.ES_SELECT_FAILURE);
        }
    }

    public List<QuestionESVO> refreshES() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if (questionList.isEmpty()) {
            return ListUtil.empty();
        }
        // 数据库存在数据，更新到ES中
        List<QuestionESVO> questionESVOS = BeanUtil.copyToList(questionList, QuestionESVO.class);
        saveToES(questionESVOS);
        return questionESVOS;
    }

    public void saveToES(List<QuestionESVO> questionESVOS) {
        // 创建 BulkRequest
        BulkRequest bulkRequest = new BulkRequest();

        // 遍历 questionESVOS 列表，逐个添加到 BulkRequest
        for (QuestionESVO questionESVO : questionESVOS) {
            // 将 QuestionESVO 对象转换为 JSON 字符串
            String jsonString = JSON.toJSONString(questionESVO);

            // 创建 IndexRequest
            IndexRequest indexRequest = new IndexRequest(Constants.ES_INDEX)
                    .id(String.valueOf(questionESVO.getQuestionId())) // 设置文档 ID，通常使用业务主键
                    .source(jsonString, XContentType.JSON); // 设置文档内容
            // 将 IndexRequest 添加到 BulkRequest
            bulkRequest.add(indexRequest);
        }
        try {
            // 执行批量插入操作
            BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            // 检查是否有失败的请求
            if (bulkResponse.hasFailures()) {
                throw new ServiceException(ResultCode.ES_SAVE_FAILURE);
            }
        } catch (IOException e) {
            throw new ServiceException(ResultCode.ES_SAVE_FAILURE);
        }
    }
}
